import { defineStore } from 'pinia';
import axios from 'axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}'),
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userProfile: (state) => state.user,
  },

  actions: {
    // 设置认证信息
    setAuth(token, user) {
      this.token = token;
      this.user = user;
      
      // 保存到本地存储
      localStorage.setItem('token', token);
      localStorage.setItem('user', JSON.stringify(user));
      
      // 设置 axios 默认请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    },

    // 清除认证信息
    clearAuth() {
      this.token = '';
      this.user = {};
      
      // 从本地存储中移除
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      
      // 移除请求头中的认证信息
      delete axios.defaults.headers.common['Authorization'];
    },

    // 登录操作
    async login(credentials) {
      try {
        // 这里应该调用你的实际登录 API
        const response = await axios.post('/api/login', credentials);
        const { token, user } = response.data;
        
        this.setAuth(token, user);
        return true;
      } catch (error) {
        console.error('登录失败:', error);
        return false;
      }
    },

    // 注册操作
    async register(userData) {
      try {
        // 这里应该调用你的实际注册 API
        const response = await axios.post('/api/register', userData);
        const { token, user } = response.data;
        
        this.setAuth(token, user);
        return true;
      } catch (error) {
        console.error('注册失败:', error);
        return false;
      }
    },

    // 登出操作
    async logout() {
      try {
        // 如果需要，这里可以调用登出 API
        // await axios.post('/api/logout');
        
        this.clearAuth();
        return true;
      } catch (error) {
        console.error('登出失败:', error);
        return false;
      }
    },

    // 初始化身份验证状态（在应用启动时调用）
    initAuth() {
      const token = localStorage.getItem('token');
      if (token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      }
    }
  }
}); 